using System;
using System.Collections.Generic;
using System.Text;
using MP3Sooker.Utility;
using System.Web;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace MP3Sooker {
    internal class BaiduMp3Sooker : Sooker {
        static Dictionary<string, Pair<String, String>> dictionary {
            get {
                Dictionary<string, Pair<String, String>> retu = new Dictionary<string, Pair<String, String>> ( );
                Pair<String, String> p = new Pair<String, String> ( "http://mp3.baidu.com/m?f=ms&rn=&tn=baidump3&ct=134217728&word=(?)&lm=0", "gbk" );
                retu.Add ( "baidu", p );
                return retu;
            }
        }

        IHtmlParser htmlParser = new RegexHtmlParser ( );

        override public List<SearchResult> Search ( String searchString ) {
            Pair<String, String> p = dictionary["baidu"];
            String mp3NameEncoding = HttpUtility.UrlEncode ( searchString, System.Text.Encoding.GetEncoding ( p.second ) );
            String url = p.first.Replace ( "(?)", mp3NameEncoding );
            String html = getHtml ( url, dictionary["baidu"].second );
            List<SearchResult> mp3urllist = htmlParser.getMp3UrlList ( html );
            return mp3urllist;
        }

        override public Uri FindReal ( string url ) {
            String html = getHtml ( url, dictionary["baidu"].second );
            String songUrl = htmlParser.getMp3Url ( html );
            if ( songUrl == null ) {
                return null;
            }
            try {
                Uri uri = new Uri ( songUrl );
                return uri;
            } catch ( Exception ) {
            }
            return null;
        }
    }
}
